package cn.edu.zjut.mina.service.impl;

import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Service;

import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.service.IIPService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.UserMap;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
@Service("iPService")
public class IPServiceImpl implements IIPService{
	
	/**
	 * 用于存放用户信息的集合
	 */
	private final UserMap userMap = UserMap.getInstance();
	
	public JMessageProtocalRes getIp(StandardFormat inJson, IoSession session) {
		//System.out.println("execute --GetIp()-- method.");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		UserInfo user = userMap.get(inJson.userId).user;
		if (user == null) {
			System.out.println(DateUtils.getTime() + "获取用户ip，用户为null");
			outJson.userId = inJson.userId;
			outJson.resultInfo = ResultInfoConstUtils.GETIP_USERNULLINFO;
			outJson.result = false;
		} else {
			synchronized(user) {//参考java编程思想 689页
				outJson.userId = inJson.userId;
				outJson.ip = user.getIp();
				outJson.result = true;
			}
		}
		
		res.setResultCode(ProtocalRegulation.GETIP);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}
}
